// 目录树管理器
class DirectoryTreeManager {
    constructor() {
        this.currentTree = null;
        this.expandedNodes = new Set();
        this.init();
    }

    init() {
        this.bindEvents();
        this.loadDefaultTree();
    }

    bindEvents() {
        // 获取目录树按钮
        const getTreeBtn = document.getElementById('get-directory-tree-btn');
        if (getTreeBtn) {
            getTreeBtn.addEventListener('click', () => this.getDirectoryTree());
        }

        // 搜索目录树按钮
        const searchTreeBtn = document.getElementById('search-directory-tree-btn');
        if (searchTreeBtn) {
            searchTreeBtn.addEventListener('click', () => this.searchDirectoryTree());
        }

        // 展开/折叠所有按钮
        const expandAllBtn = document.getElementById('expand-all-btn');
        if (expandAllBtn) {
            expandAllBtn.addEventListener('click', () => this.expandAll());
        }

        const collapseAllBtn = document.getElementById('collapse-all-btn');
        if (collapseAllBtn) {
            collapseAllBtn.addEventListener('click', () => this.collapseAll());
        }
    }

    async loadDefaultTree() {
        try {
            // 尝试加载当前工作目录的目录树
            // 使用空字符串，让后端使用配置的索引目录
            await this.getDirectoryTreeByPath('');
        } catch (error) {
            console.error('Failed to load default directory tree:', error);
        }
    }

    async getDirectoryTree() {
        const directoryElement = document.getElementById('directory-path');
        const directory = directoryElement ? directoryElement.value.trim() : '';
        // 允许空目录路径，后端会使用配置的索引目录作为默认值
        await this.getDirectoryTreeByPath(directory);
    }

    async getDirectoryTreeByPath(directory) {
        try {
            this.showLoading('正在获取目录树...');

            // 添加空值检查，防止元素不存在导致的错误
            let maxDepth = 0;
            const maxDepthElement = document.getElementById('max-depth');
            if (maxDepthElement) {
                maxDepth = parseInt(maxDepthElement.value) || 0;
            }
            
            let showHidden = false;
            const showHiddenElement = document.getElementById('show-hidden');
            if (showHiddenElement) {
                showHidden = showHiddenElement.checked;
            }
            
            let onlyIndexed = false;
            const onlyIndexedElement = document.getElementById('only-indexed');
            if (onlyIndexedElement) {
                onlyIndexed = onlyIndexedElement.checked;
            }
            
            let fileFilter = '';
            const fileFilterElement = document.getElementById('file-filter');
            if (fileFilterElement) {
                fileFilter = fileFilterElement.value.trim();
            }

            const params = new URLSearchParams({
                directory: directory,
                max_depth: maxDepth.toString(),
                show_hidden: showHidden.toString(),
                only_indexed: onlyIndexed.toString()
            });

            if (fileFilter) {
                params.append('file_filter', fileFilter);
            }

            const response = await window.apiClient.get(`/api/v1/directory-tree?${params.toString()}`);
            
            if (response.success) {
                this.currentTree = response.data;
                this.renderDirectoryTree(response.data);
                this.showSuccess(`目录树获取成功，共 ${response.data.total_files} 个文件，${response.data.total_dirs} 个目录`);
            } else {
                this.showError(response.message || '获取目录树失败');
            }
        } catch (error) {
            console.error('Get directory tree error:', error);
            this.showError('获取目录树失败: ' + error.message);
        } finally {
            this.hideLoading();
        }
    }

    async searchDirectoryTree() {
        const directoryElement = document.getElementById('directory-path');
        const directory = directoryElement ? directoryElement.value.trim() : '';
        
        const patternElement = document.getElementById('search-pattern');
        const pattern = patternElement ? patternElement.value.trim() : '';
        
        if (!directory) {
            this.showError('请输入目录路径');
            return;
        }

        if (!pattern) {
            this.showError('请输入搜索模式');
            return;
        }

        try {
            this.showLoading('正在搜索目录树...');

            let maxDepth = 0;
            const maxDepthElement = document.getElementById('max-depth');
            if (maxDepthElement) {
                maxDepth = parseInt(maxDepthElement.value) || 0;
            }
            
            let showHidden = false;
            const showHiddenElement = document.getElementById('show-hidden');
            if (showHiddenElement) {
                showHidden = showHiddenElement.checked;
            }
            
            let onlyIndexed = false;
            const onlyIndexedElement = document.getElementById('only-indexed');
            if (onlyIndexedElement) {
                onlyIndexed = onlyIndexedElement.checked;
            }
            
            let searchType = 'name';
            const searchTypeElement = document.getElementById('search-type');
            if (searchTypeElement) {
                searchType = searchTypeElement.value;
            }
            
            let caseSensitive = false;
            const caseSensitiveElement = document.getElementById('case-sensitive');
            if (caseSensitiveElement) {
                caseSensitive = caseSensitiveElement.checked;
            }

            const requestData = {
                directory: directory,
                max_depth: maxDepth,
                show_hidden: showHidden,
                only_indexed: onlyIndexed,
                pattern: pattern,
                search_type: searchType,
                case_sensitive: caseSensitive
            };

            const response = await window.apiClient.post('/api/v1/directory-tree/search', requestData);
            
            if (response.success) {
                this.currentTree = response.data;
                this.renderDirectoryTree(response.data);
                this.showSuccess(`搜索完成，找到 ${response.data.filtered_files} 个匹配的文件`);
            } else {
                this.showError(response.message || '搜索目录树失败');
            }
        } catch (error) {
            console.error('Search directory tree error:', error);
            this.showError('搜索目录树失败: ' + error.message);
        } finally {
            this.hideLoading();
        }
    }

    renderDirectoryTree(treeData) {
        const container = document.getElementById('directory-tree-container');
        if (!container) return;

        // 清空容器
        container.innerHTML = '';

        // 创建树形结构
        if (treeData.root) {
            const treeElement = this.createTreeNode(treeData.root, 0);
            container.appendChild(treeElement);
        }

        // 显示统计信息
        this.updateTreeStats(treeData);
    }

    createTreeNode(node, level) {
        const nodeElement = document.createElement('div');
        nodeElement.className = 'tree-node';
        nodeElement.style.marginLeft = `${level * 20}px`;

        const nodeContent = document.createElement('div');
        nodeContent.className = 'tree-node-content';

        // 创建展开/折叠按钮
        if (node.type === 'directory' && node.children && node.children.length > 0) {
            const toggleBtn = document.createElement('span');
            toggleBtn.className = 'tree-toggle';
            toggleBtn.textContent = node.is_expanded ? '▼' : '▶';
            toggleBtn.addEventListener('click', () => this.toggleNode(node, nodeElement));
            nodeContent.appendChild(toggleBtn);
        } else {
            const spacer = document.createElement('span');
            spacer.className = 'tree-spacer';
            spacer.textContent = '  ';
            nodeContent.appendChild(spacer);
        }

        // 创建图标
        const icon = document.createElement('span');
        icon.className = 'tree-icon';
        if (node.type === 'directory') {
            icon.textContent = '📁';
        } else {
            icon.textContent = this.getFileIcon(node.extension);
        }
        nodeContent.appendChild(icon);

        // 创建名称
        const name = document.createElement('span');
        name.className = 'tree-name';
        name.textContent = node.name;
        if (node.is_indexed) {
            name.classList.add('indexed');
        }
        nodeContent.appendChild(name);

        // 创建文件信息
        if (node.type === 'file') {
            const info = document.createElement('span');
            info.className = 'tree-info';
            info.textContent = ` (${this.formatFileSize(node.size)})`;
            nodeContent.appendChild(info);
        }

        nodeElement.appendChild(nodeContent);

        // 创建子节点容器
        if (node.children && node.children.length > 0) {
            const childrenContainer = document.createElement('div');
            childrenContainer.className = 'tree-children';
            childrenContainer.style.display = node.is_expanded ? 'block' : 'none';

            node.children.forEach(child => {
                const childElement = this.createTreeNode(child, level + 1);
                childrenContainer.appendChild(childElement);
            });

            nodeElement.appendChild(childrenContainer);
        }

        return nodeElement;
    }

    toggleNode(node, nodeElement) {
        node.is_expanded = !node.is_expanded;
        
        const toggleBtn = nodeElement.querySelector('.tree-toggle');
        const childrenContainer = nodeElement.querySelector('.tree-children');
        
        if (toggleBtn) {
            toggleBtn.textContent = node.is_expanded ? '▼' : '▶';
        }
        
        if (childrenContainer) {
            childrenContainer.style.display = node.is_expanded ? 'block' : 'none';
        }
    }

    expandAll() {
        if (this.currentTree && this.currentTree.root) {
            this.setAllNodesExpanded(this.currentTree.root, true);
            this.renderDirectoryTree(this.currentTree);
        }
    }

    collapseAll() {
        if (this.currentTree && this.currentTree.root) {
            this.setAllNodesExpanded(this.currentTree.root, false);
            this.renderDirectoryTree(this.currentTree);
        }
    }

    setAllNodesExpanded(node, expanded) {
        if (node.type === 'directory') {
            node.is_expanded = expanded;
        }
        
        if (node.children) {
            node.children.forEach(child => {
                this.setAllNodesExpanded(child, expanded);
            });
        }
    }

    getFileIcon(extension) {
        const iconMap = {
            '.js': '📄',
            '.ts': '📄',
            '.html': '🌐',
            '.css': '🎨',
            '.md': '📝',
            '.txt': '📄',
            '.json': '📋',
            '.xml': '📋',
            '.yml': '📋',
            '.yaml': '📋',
            '.go': '🐹',
            '.py': '🐍',
            '.java': '☕',
            '.c': '⚙️',
            '.cpp': '⚙️',
            '.h': '⚙️',
            '.png': '🖼️',
            '.jpg': '🖼️',
            '.jpeg': '🖼️',
            '.gif': '🖼️',
            '.svg': '🖼️',
            '.pdf': '📕',
            '.zip': '📦',
            '.tar': '📦',
            '.gz': '📦'
        };
        
        return iconMap[extension.toLowerCase()] || '📄';
    }

    formatFileSize(bytes) {
        if (bytes === 0) return '0 B';
        
        const k = 1024;
        const sizes = ['B', 'KB', 'MB', 'GB'];
        const i = Math.floor(Math.log(bytes) / Math.log(k));
        
        return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + ' ' + sizes[i];
    }

    updateTreeStats(treeData) {
        const statsContainer = document.getElementById('tree-stats');
        if (!statsContainer) return;

        statsContainer.innerHTML = `
            <div class="stats-item">
                <span class="stats-label">总文件数:</span>
                <span class="stats-value">${treeData.total_files}</span>
            </div>
            <div class="stats-item">
                <span class="stats-label">总目录数:</span>
                <span class="stats-value">${treeData.total_dirs}</span>
            </div>
            <div class="stats-item">
                <span class="stats-label">已索引文件:</span>
                <span class="stats-value">${treeData.indexed_files}</span>
            </div>
            <div class="stats-item">
                <span class="stats-label">过滤后文件:</span>
                <span class="stats-value">${treeData.filtered_files}</span>
            </div>
            <div class="stats-item">
                <span class="stats-label">处理耗时:</span>
                <span class="stats-value">${treeData.took}ms</span>
            </div>
        `;
    }

    showLoading(message) {
        const loadingElement = document.getElementById('loading');
        if (loadingElement) {
            loadingElement.textContent = message;
            loadingElement.style.display = 'block';
        }
    }

    hideLoading() {
        const loadingElement = document.getElementById('loading');
        if (loadingElement) {
            loadingElement.style.display = 'none';
        }
    }

    showSuccess(message) {
        this.showMessage(message, 'success');
    }

    showError(message) {
        this.showMessage(message, 'error');
    }

    showMessage(message, type) {
        const messageElement = document.getElementById('message');
        if (messageElement) {
            messageElement.textContent = message;
            messageElement.className = `message ${type}`;
            messageElement.style.display = 'block';
            
            setTimeout(() => {
                messageElement.style.display = 'none';
            }, 5000);
        }
    }
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', () => {
    if (!window.directoryTreeManager) {
        window.directoryTreeManager = new DirectoryTreeManager();
    }
});